package com.sync.data.common.listener;

import cn.hutool.core.util.ObjectUtil;
import com.sync.data.common.annotation.FieldProps;
import com.sync.data.common.util.ClassUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.NullValueInNestedPathException;
import org.springframework.beans.factory.annotation.Configurable;

import javax.persistence.PostLoad;
import javax.persistence.Transient;
import java.lang.reflect.Field;
import java.util.List;

/**
 * Dict监听
 * @author liquanchang
 */
@Configurable
@Slf4j
public class ReferenceListener {

    @PostLoad
    public void prePersist(Object entity) {

        List<Field> fields = ClassUtils.getAllFields(entity.getClass());

        for(Field field : fields){
            FieldProps fieldProps = field.getAnnotation(FieldProps.class);
            Transient aTransient = field.getAnnotation(Transient.class);
            if(ObjectUtil.isNotEmpty(fieldProps)){
                if(!"".equals(fieldProps.reference()) && aTransient != null){
                    String reference = fieldProps.reference();
                    try {
                        BeanWrapper sourceWrapper = new BeanWrapperImpl(entity);

                        // 初始化嵌套路径（必要时也可以设置 autoGrowNestedPaths = true）
                        Object value = sourceWrapper.getPropertyValue(reference);

                        if (value != null) {
                            // 写入到目标字段
                            BeanWrapper targetWrapper = new BeanWrapperImpl(entity);
                            targetWrapper.setPropertyValue(field.getName(), value);
                        }
                    } catch (NullValueInNestedPathException ignored) {
                    }
                }
            }
        }
    }
}
